import './Style.css';
import React, { useState ,useEffect,useRef} from 'react';
import axios from 'axios';
import moment from 'moment';
function Message({id,content,dateString,isSelf}){
 return <>
            <div className="comment" key={id} >
                <strong>{id}:</strong>
                <p style={{background:isSelf?'#4CAF50':'darkgray'}}>{content}</p>
                <span>{dateString}</span>
            </div>
	</>;
}
export default function Content(){
  const [msgs, setMsgs] = useState([]);
  const [sendMsgs,setSendMsgs] =useState([]);
  const ws = useRef(null);
  const inputRef = useRef(null);
  const [targetId,setTargetId] =useState();
  useEffect(() => {
    ws.current = new WebSocket('ws://localhost:8000/ws');
    
    ws.current.onopen = (event) => {
      const message={type:0,userId:sessionStorage.getItem('userId'),password:123456};
      ws.current.send(JSON.stringify(message));
      console.log('WebSocket is open now.');
    };

    ws.current.onmessage = (event) => {
      console.log(event.data);
      const message=JSON.parse(event.data);
      setMsgs((prevMsgs) => [...prevMsgs, message]);
    };

    ws.current.onclose = () => {
      console.log('WebSocket is closed now.');
    };

    ws.current.onerror = (error) => {
      console.error('WebSocket error: ', error);
    };

    // 在组件卸载时关闭 WebSocket 连接
    return () => {
      ws.current.close();
    };
  }, []);

  const send = () => {
    const message = {type:1,targetId:targetId,content:inputRef.current.value,srcId:sessionStorage.getItem("userId")};
    const formattedTime = moment().format('YYYYMMDDHHmmss');
    const srcMessage={id:"To:"+targetId,content:inputRef.current.value,dataString:formattedTime};
    setSendMsgs((prevMsgs) => [...prevMsgs,srcMessage]);
    //清空输入框
    inputRef.current.value="";
    if (ws.current.readyState === WebSocket.OPEN) {
        ws.current.send(JSON.stringify(message));
    } else {
      console.log('WebSocket connection is not open.');
    }
  };
  const handlerClick=(targetId)=>{
    setTargetId(targetId);
  }
	return (
  <div className='container'>
  <LeftSide onTarget={handlerClick}/>
  <div className='content'>
    <div className='receive'>
      <h1>收到消息</h1>
		{msgs.map((item,index)=>(
			<Message id={item.id} content={item.content} dateString={item.date} isSelf={false}/>
		))}
    </div>
    <div className='send'>
      <h1>发送消息</h1>
		{sendMsgs.map((item,index)=>(
			<Message id={item.id} content={item.content} dateString={item.date} isSelf={true}/>
		))}
		  <div className='ib'>
        <input ref={inputRef} type="text" id="input" placeholder={'向'+targetId+'发送消息'}/>
		    <button type='submit' onClick={send}>发送</button>
      </div>
		</div>

	</div>
  </div>)
}
function LeftSide({onTarget}){
  const [all,setAll] =useState([]);
  const [onlineUsers,setOU] =useState([]);
  const [targetId,setTargetId] =useState();
  useEffect(()=>{
    axios({
      method:'GET',
      url:'http://localhost:8080/query/allusers'
    }).then(res=>{
      setAll(res.data);
    },error => {
      console.log('错误', error.message)
  });
    axios.get('http://localhost:8080/query/onlineusers')
    .then(res=>{
      setOU(res.data);
    })
  },[]);
  const usersWithStatus = all.map(user => ({
    ...user,
    isOnline: onlineUsers.some(onlineUser => onlineUser === user.userId)
}));
function choose(targetId){
  setTargetId(targetId);
}
  return( <div className='left_side'>
    <h1>用户列表</h1>
    <hr/>
      {usersWithStatus.map((item,index)=>(
        <ul>
          <li key={index} style={{ color: item.isOnline ? 'green' : 'black' }} onClick={()=>onTarget(item.userId)}>{item.userId}{item.isOnline ? '(在线)' : '(离线)'}</li>
        </ul>
      ))}
  </div>)
}
